//
//  Date.swift
//  EyeVisionForPatients
//
//  Created by TT on 2020/2/10.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import Foundation

extension Date {
    init?(parse dateString: String, format: String = "yyyy-MM-dd", locale: String = "zh_CN") {
        let dateFormatter = DateFormatter()
        dateFormatter.calendar = Calendar.autoupdatingCurrent
        dateFormatter.locale = Locale(identifier: locale)
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.dateFormat = format
        guard let parsed = dateFormatter.date(from: dateString) else {
            return nil
        }
        
        self = parsed
    }
    
    var milliseconds: TimeInterval {
        let int = Int(self.timeIntervalSince1970 * 1000)
        return TimeInterval(int)
    }
    
    /// 获取时间戳
    var millistamp: String {
        let timeInterval = Int(self.timeIntervalSince1970 * 1000)
        return "\(timeInterval)"
    }
    
    func toString(format: String = "yyyy-MM-dd HH:mm:ss", locale: String = "zh_CN") -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: self)
    }

    static func stringToDate(_ string: String, dateFormat: String = "yyyy-MM-dd HH:mm:ss") -> Date {
        let formatter = DateFormatter()
        formatter.dateFormat = dateFormat
        guard let date = formatter.date(from: string) else { return Date() }
        return date
    }

    static func dateStringFormatToString(_ string: String, inputFormat: String = "yyyy-MM-dd HH:mm:ss", outputFormat: String = "yyyy-MM-dd HH:mm:ss") -> String {
        let date = Date.stringToDate(string, dateFormat: inputFormat)
        let string = date.toString(format: outputFormat)
        return string
    }
    
    func weekDay() -> String {
        let weekDay = Calendar.current.component(.weekday, from: self)
        switch weekDay {
        case 2:
            return "周一"
        case 3:
            return "周二"
        case 4:
            return "周三"
        case 5:
            return "周四"
        case 6:
            return "周五"
        case 7:
            return "周六"
        case 1:
            return "周日"
        default:
            return ""
        }
    }
    
    /// 当前日
    var day: Int {
        return Calendar.current.component(.day, from: self)
    }
    
    /// 当前月
    var month: Int {
        return Calendar.current.component(.month, from: self)
    }
    
    /// 当前年
    var year: Int {
        return Calendar.current.component(.year, from: self)
    }
    
    /// 当前月的天数
    var daysOfCurrentMonth: Int {
        guard let range = Calendar.current.range(of: .day, in: .month, for: self) else { return 0 }
        return range.count
    }
    
    static func weekModels(weekNum num: Int = 1, separateAmPm: Bool = false, containToday: Bool = true) -> [DateWeekModel] {
        let count = num * 7 - (containToday ? 0 : 1)
        var timeIntervals = ["am", "pm"]
        if separateAmPm == false {
            timeIntervals = ["am"]
        }
        let nowDate = Date()
        var weekModels = [DateWeekModel]()
        for i in 0..<count {
            let nextDate = Calendar.current.date(byAdding: DateComponents(day: i + (containToday ? 0 : 1)), to: nowDate) ?? Date()
            let yearMonthDay = nextDate.toString()
            let monthDay = nextDate.toString(format: "MM-dd")
            let weekDay = nextDate.weekDay()
            for j in 0..<timeIntervals.count {
                let model = DateWeekModel(yearMonthDay: yearMonthDay,
                                          monthDay: monthDay,
                                          weekDay: weekDay,
                                          timeInterval: timeIntervals[j])
                weekModels.append(model)
            }
        }
        weekModels.insert(DateWeekModel(), at: 0)
        return weekModels
    }
    
    static func messageAgoSinceDate(_ date: Date) -> String {
        return self.timeAgoSinceDate(date, numericDates: true)
    }
    
    static func timeAgoSinceDate(_ date: Date, numericDates: Bool) -> String {
        let calendar = Calendar.current
        let now = Date()
        let earliest = (now as NSDate).earlierDate(date)
        let latest = (earliest == now) ? date : now
        let components:DateComponents = (calendar as NSCalendar).components([
            NSCalendar.Unit.minute,
            NSCalendar.Unit.hour,
            NSCalendar.Unit.day,
            NSCalendar.Unit.weekOfYear,
            NSCalendar.Unit.month,
            NSCalendar.Unit.year,
            NSCalendar.Unit.second
            ], from: earliest, to: latest, options: NSCalendar.Options())
        
        if (components.year! >= 2) {
            return "\(String(describing: components.year)) 年前"
        } else if (components.year! >= 1){
            if (numericDates){
                return "1 年前"
            } else {
                return "去年"
            }
        } else if (components.month! >= 2) {
            return "\(String(describing: components.month)) 月前"
        } else if (components.month! >= 1){
            if (numericDates){
                return "1 个月前"
            } else {
                return "上个月"
            }
        } else if (components.weekOfYear! >= 2) {
            return "\(String(describing: components.weekOfYear)) 周前"
        } else if (components.weekOfYear! >= 1){
            if (numericDates){
                return "1 周前"
            } else {
                return "上一周"
            }
        } else if (components.day! >= 2) {
            return "\(String(describing: components.day)) 天前"
        } else if (components.day! >= 1){
            if (numericDates){
                return "1 天前"
            } else {
                return "昨天"
            }
        } else if (components.hour! >= 2) {
            return "\(String(describing: components.hour)) 小时前"
        } else if (components.hour! >= 1){
            return "1 小时前"
        } else if (components.minute! >= 2) {
            return "\(String(describing: components.minute)) 分钟前"
        } else if (components.minute! >= 1){
            return "1 分钟前"
        } else if (components.second! >= 3) {
            return "\(String(describing: components.second)) 秒前"
        } else {
            return "刚刚"
        }
    }
    
    // 秒时间戳转时间函数
    static func timeStampToString(timeStamp: Int) -> String {
        let hours = Int(timeStamp / 3600)
        let minute = Int((timeStamp % 3600) / 60)
        let second = Int(timeStamp % 60)
        
        if hours > 0 {
            return String(format: "%02d时%02d分%02d秒", hours, minute, second)
        }
        
        if minute > 0 {
            return String(format: "%02d分%02d秒", minute, second)
        }
        
        return String(format: "%02d秒", second)
    }
}

extension Date {
    var chatTimeString: String {
        let calendar = Calendar.current
        let now = Date()
        let unit: NSCalendar.Unit = [.minute, .hour, .day, .month, .year]
        
        let nowComponents = (calendar as NSCalendar).components(unit, from: now)
        let targetComponents = (calendar as NSCalendar).components(unit, from: self)
        
        let year = nowComponents.year! - targetComponents.year!
        let month = nowComponents.month! - targetComponents.month!
        let day = nowComponents.day! - targetComponents.day!
        
        if year != 0 {
            return String(format: "%zd年%zd月%zd日 %02d:%02d", targetComponents.year!, targetComponents.month!, targetComponents.day!, targetComponents.hour!, targetComponents.minute!)
        } else {
            if (month > 0 || day > 7) {
                return String(format: "%zd月%zd日 %02d:%02d", targetComponents.month!, targetComponents.day!, targetComponents.hour!, targetComponents.minute!)
            } else if (day > 2) {
                return String(format: "%@ %02d:%02d",self.weekDay(), targetComponents.hour!, targetComponents.minute!)
            } else if (day == 2) {
                if targetComponents.hour! < 12 {
                    return String(format: "前天上午 %02d:%02d", targetComponents.hour!, targetComponents.minute!)
                } else if targetComponents.hour == 12 {
                    return String(format: "前天下午 %02d:%02d", targetComponents.hour!, targetComponents.minute!)
                } else {
                    return String(format: "前天下午 %02d:%02d", targetComponents.hour! - 12, targetComponents.minute!)
                }
            } else if (day == 1) {
                if targetComponents.hour! < 12 {
                    return String(format: "昨天上午 %02d:%02d", targetComponents.hour!, targetComponents.minute!)
                } else if targetComponents.hour == 12 {
                    return String(format: "昨天下午 %02d:%02d", targetComponents.hour!, targetComponents.minute!)
                } else {
                    return String(format: "昨天下午 %02d:%02d", targetComponents.hour! - 12, targetComponents.minute!)
                }
            } else if (day == 0){
                if targetComponents.hour! < 12 {
                    return String(format: "上午 %02d:%02d", targetComponents.hour!, targetComponents.minute!)
                } else if targetComponents.hour == 12 {
                    return String(format: "下午 %02d:%02d", targetComponents.hour!, targetComponents.minute!)
                } else {
                    return String(format: "下午 %02d:%02d", targetComponents.hour! - 12, targetComponents.minute!)
                }
            } else {
                return ""
            }
        }
    }
}
